import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Objects;

/**
 * @author sk.z
 */
public class DrawCurve extends JApplet {
    private static final long serialVersionUID = 7199803776256352698L;

    private static final int WIDTH = 800;
    private static final int HEIGHT = 800;
    private static final int ORIGIN_X = 400;
    private static final int ORIGIN_Y = 400;

    public static void main(String[] args) {
        JFrame jFrame = new JFrame("Draw Coordinate");

        JApplet applet = new DrawCurve();
        jFrame.getContentPane().add("Center", applet);

        jFrame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        jFrame.setSize(new Dimension(WIDTH, HEIGHT));
        jFrame.setResizable(false);
        jFrame.setVisible(true);
    }

    public void init() {
        setBackground(Color.white);
        setForeground(Color.black);
    }

    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        drawCoordinateLine(g2);

        g2.setColor(Color.GREEN);
        Equation X_ADD_Y_EQ1 = new Equation();
        Integer t;

        for (int x = -400; x < WIDTH; x++) {
            t = X_ADD_Y_EQ1.getY(x);
            drawPoint(g2, transX(x), transY(t));
        }

        for (int y = -400; y < HEIGHT; y++) {
            t = X_ADD_Y_EQ1.getX(y);
            if (Objects.isNull(t)){
                continue;
            }
            drawPoint(g2, transX(t), transY(y));
            drawPoint(g2, transX(-t), transY(y));
        }

    }

    //绘制坐标轴线
    private void drawCoordinateLine(Graphics2D graphics) {
        graphics.drawLine(0, ORIGIN_Y, WIDTH, ORIGIN_Y);
        graphics.drawLine(ORIGIN_X, 0, ORIGIN_X, HEIGHT);
    }

    //转换系坐标到屏幕坐标
    private int transX(int x) {
        return x + ORIGIN_X;
    }

    private int transY(int y) {
        return -y + ORIGIN_Y;
    }

    private void drawPoint(Graphics2D graphics, int x, int y) {
        graphics.drawLine(x, y, x, y);
    }

    private static class Equation {
        // x^2 + y = 5;

        // y=5-x^2
        private int getY(int x) {
            return 300 - (int) Math.pow(x, 2);
        }

        // x=5-y
        private Integer getX(int y) {
            if ((300 - y) < 0) {
                return null;
            }
            return (int) Math.sqrt(300 - y);
        }
    }

}
